package 每日一题;

import org.junit.Test;

public class 比较版本号 {

    public int compareVersion(String version1, String version2) {
        String[] a1 = version1.split("\\.");
        String[] a2 = version2.split("\\.");

        for(int n = 0; n < Math.max(a1.length, a2.length); n++){
            int i = (n < a1.length ? Integer.valueOf(a1[n]) : 0);
            int j = (n < a2.length ? Integer.valueOf(a2[n]) : 0);
            if(i < j) return -1;
            else if(i > j) return 1;
        }
        return 0;
    }
    //虽然能通过，但还是有很大的改进空间。争取向上面的一样简洁
    public int compareVersion1(String version1, String version2) {
        String[] s1 = version1.split("\\.");
        String[] s2 = version2.split("\\.");
        int[] ints1 = toInt(s1);
        int[] ints2 = toInt(s2);
        int m = ints1.length;
        int n = ints2.length;
        int len=m>n?n:m;
        for (int i = 0; i < len; i++) {
            if (ints1[i]>ints2[i])
                return 1;
            else if (ints1[i]<ints2[i])
                return -1;
        }
        if (m>n){
            for (int i = len; i < m; i++) {
                if (ints1[i]!=0)
                    return 1;
            }
        }
        else {
            for (int i = len; i < n; i++) {
                if (ints2[i]!=0)
                    return -1;
            }
        }
        return 0;
    }
    public int[] toInt(String[] s){
        int[] ints = new int[s.length];
        for (int i = 0; i < s.length; i++) {
            int j=0;
            while (s[i].charAt(j)==0) {
                j++;
                if (j == s[i].length())
                    break;
            }
            if (j == s[i].length())
                continue;
            String substring = s[i].substring(j, s[i].length());
            int parseInt = Integer.parseInt(substring);
            ints[i]=parseInt;
        }
        return ints;
    }
    @Test
    public void test(){
        String s="00001";
        int parseInt = Integer.parseInt(s);
        System.out.println(parseInt);
        System.out.println(compareVersion("0.1", "1.1"));
    }
}
